//
// Created by gastonfeng on 2022/11/3.
//

#ifndef RTE_KB1288_BLE_PASSPORT_H
#define RTE_KB1288_BLE_PASSPORT_H

#include "kSerial.h"
#include "smodule.h"

class BLE_PassPort : public kSerial, public smodule
{
public:
    int type() override { return pb_object_ble_tag; }

    int begin(uint32_t tick) override;

#ifdef __PLATFORMIO_BUILD_DEBUG__
    int dev_test(uint32_t) override;
#endif

    int diag(uint32_t) override;

    int run(uint32_t) override;

    int availableWrite();

    const char *name() override { return "BLE_PassPort"; }

    int rts;
    int cts;
    int led_slave;
    int rst;

    int begin(int rts, int cts, int led_slave, int led_master, int rst);

    int write(uint8_t ch) final
    {
        uint8_t buff = ch;
        // while (!availableWrite()) {
        //     Rtos::Delay(1);
        // }
        return kSerial::write(&buff, 1);
    }

    const char *ble_name = "PAC:" HWMODEL;

    int set_device_name(const char *name);

    String get_device_name();

    uint32_t led_master;

    String sendAT(String cmd, String param);

    bool is_AT_mode();

    int exit_AT_mode();

    int enter_AT_mode();

    int sleep(bool port_en, bool ble_en, bool warkup_en);

    int encode(pb_object *msg, pb_ostream_t *stream) override
    {
        msg->object.ble = data;
        msg->which_object = pb_object_ble_tag;
        return pb_encode(stream, pb_object_fields, msg);
    }

    int iter(pb_field_iter_t *pS) override
    {
        return pb_field_iter_begin(pS, pb_ble_info_fields, &data);
    }

    int end() override;

    pb_ble_info data;
    void *thd;
    mFirmata firm;
    bool last_state = false;

    [[noreturn]] static void thread(void *arg);

    void wakeup() const;
};

extern BLE_PassPort ble;

#endif // RTE_KB1288_BLE_PASSPORT_H
